<?php

namespace app\common\model;

use app\common\service\StatusService;
use think\Db;
use think\Model;


class PromoterGoods extends Model
{

    

    

    // 表名
    protected $name = 'promoter_goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
	    'status_text'
    ];
	
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = StatusService::$goodsStatusList;
		return $list[$value] ?? '';
	}
	
	public function goods()
	{
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function user()
	{
		return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
	
	
	/**
	 * 获取推广员正常推广的商品
	 * @param $userId
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getNormalGoodsByUserId($userId)
	{
		return Db::name('promoterGoods')->alias('pg')
			->join('goods g', 'pg.goods_id = g.id', 'left')
			->join('promoterCount pc', 'pg.user_id = pc.user_id and pc.goods_id = pg.goods_id', 'left')
			->where([
				'pg.user_id' => $userId,
				'pg.status' => StatusService::STATUS_NORMAL,
				'g.status' => StatusService::STATUS_NORMAL])
			->order(['pg.sort' => 'asc', 'pg.update_time' => 'desc'])
			->field('pg.id, pg.goods_id, g.image, g.goods_name, g.price, g.commission, g.view_commission, g.sale_number, pc.click_number, pc.order_number, pc.click_commission, pc.order_commission, g.view_commission, g.commission')
			->select();
	}
	
	protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
